<template>
  <view class="body">
    <view class="tips">
      依据国家相关法律要求，互联网就医实行实名制，为保证顺利享受健康服务，请填写真实信息，婴幼儿身份信息请查看户口本
    </view>
    <view class="data_form">
      <form>
        <view class="form_item">
          <view class="title"><text style="color: red">*</text>姓名</view>
          <input
            class="form_input"
            type="text"
            maxlength="10"
            v-model="state.userInfo.name"
            placeholder="请填写真实姓名"
            :border="false"
          />
        </view>
        <view class="form_item">
          <view class="title"><text style="color: red">*</text>证件类型</view>
          <view class="pop_select" @tap="type == 'add' ? (show2 = true) : (show2 = false)">
            <input
              class="form_input pop_input"
              style="pointer-events: none"
              v-model="state.userInfo.cardType"
              disabled
              placeholder="请输入证件类型"
              :border="false"
            />
            <image class="img_more" src="@/static/image/form-arrow-right.png" />
          </view>
        </view>
        <view class="form_item">
          <view class="title"><text style="color: red">*</text>证件号</view>
          <input
            class="form_input"
            :type="state.userInfo.cardType === '居民身份证' ? 'idcard' : 'text'"
            :disabled="type == 'update'"
            v-model="state.userInfo.idCard"
            placeholder="请正确填写证件号"
            :border="false"
          />
        </view>
        <view class="form_item">
          <view class="title"><text style="color: red">*</text>手机号</view>
          <input
            class="form_input"
            type="number"
            v-model="state.userInfo.phone"
            placeholder="请正确填写手机号"
            :border="false"
          />
        </view>
        <view v-if="state.userInfo.cardType !== '居民身份证'" class="form_item">
          <view class="title"><text style="color: red">*</text>性别</view>
          <radio-group @change="groupChange" class="radio_group">
            <view class="radio_btn" style="margin-right: 32rpx">
              <radio
                :disabled="type == 'update'"
                :checked="state.userInfo.sex == '男性'"
                color="#00d1b6"
                value="男性"
              />
              <text>男性</text>
            </view>
            <view class="radio_btn">
              <radio
                :disabled="type == 'update'"
                :checked="state.userInfo.sex == '女性'"
                color="#00d1b6"
                value="女性"
              />
              <text>女性</text>
            </view>
          </radio-group>
        </view>
        <view v-if="state.userInfo.cardType !== '居民身份证'" class="form_item">
          <view class="title"><text style="color: red">*</text>出生年月</view>
          <picker
            :disabled="type == 'update'"
            mode="date"
            :end="formatDate(new Date(), 'yyyy-MM-dd')"
            :start="'1920-01-01'"
            :value="initDate"
            @change="setBirth"
          >
            <view class="pop_select">
              <input
                class="form_input pop_input"
                style="pointer-events: none"
                v-model="state.userInfo.birthday"
                disabled
                placeholder="请选择出生年月"
                :border="false"
              />
              <image class="img_more" src="@/static/image/form-arrow-right.png" />
            </view>
          </picker>
        </view>
        <view class="form_item">
          <view class="title">Ta是你的</view>
          <view class="pop_select" @tap="show = true">
            <input
              class="form_input pop_input"
              style="pointer-events: none"
              v-model="state.userInfo.relation"
              disabled
              placeholder="选择与本人关系 (选填)"
              :border="false"
            />
            <image class="img_more" src="@/static/image/form-arrow-right.png" />
          </view>
        </view>
      </form>
    </view>
    <up-popup :show="show" :round="16" mode="bottom" closeable @close="show = false">
      <view class="title">请选择与本人关系</view>
      <view class="lists">
        <view
          v-for="(item, index) in relationList"
          :key="index"
          class="item"
          @tap="selectRelation(item)"
        >
          {{ item.name }}
        </view>
      </view>
    </up-popup>
    <up-popup :show="show2" :round="16" mode="bottom" closeable @close="show2 = false">
      <view class="title">请选择证件类型</view>
      <view class="lists">
        <view
          v-for="(item, index) in typeList"
          :key="index"
          class="item"
          @tap="selectCardType(item)"
        >
          {{ item.name }}
        </view>
      </view>
    </up-popup>
    <view class="isdefault">
      <view class="label">设为默认就诊人</view>
      <switch
        :checked="state.userInfo.isDefault"
        @change="switchChange"
        color="#00d1b6"
        style="transform: scale(0.8)"
      />
    </view>
    <view class="fixed">
      <button v-if="type == 'update'" @tap="deleteFamily" class="delete_btn">删除</button>
      <button class="confirm_btn" @tap="save">保存</button>
    </view>
    <up-modal
      :show="modalShow"
      :title="'提示'"
      :closeOnClickOverlay="true"
      :showCancelButton="true"
      :confirmColor="'#FF503D'"
      @confirm="deletePatient"
      @close="modalShow = false"
      @cancel="modalShow = false"
    >
      <view
        style="width: 100%; font-size: 30rpx; font-weight: 400; color: #4e5969; text-align: center"
        >确认要删除该就诊人吗?</view
      >
    </up-modal>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { add_patient, query_patient_detail, del_patient, query_patient } from '@/api/family'
import { base_info } from '@/api/moreMessage'
import { onLoad, onShow } from '@dcloudio/uni-app'
import store from '@/store'
import { validatorIdcard } from '@/utils/tools'
import { formatDate } from '@/utils/util'

const state = reactive({
  userInfo: {
    name: '',
    cardType: '',
    idCard: '',
    phone: '',
    sex: '',
    birthday: '',
    relation: '',
    isDefault: false
  }
})
const isDefault = ref(false) // 作判断用默认
const modalShow = ref(false)
const show = ref(false)
const show2 = ref(false)
const initDate = ref(formatDate(new Date('2000-01-01'), 'yyyy-MM-dd'))
const type = ref('')
const patientInfo = ref({})
const info = ref({})
const relationList = ref([
  {
    name: '父母',
    value: 'PARENT'
  },
  {
    name: '子女',
    value: 'CHILD'
  },
  {
    name: '配偶',
    value: 'SPOUSE'
  },
  {
    name: '其他',
    value: 'OTHER'
  },
  {
    name: '本人',
    value: 'SELF'
  }
])
const typeList = ref([
  {
    name: '居民身份证',
    value: '01'
  },
  {
    name: '护照',
    value: '03'
  }
])

onLoad((option) => {
  type.value = option.type ? option.type : ''
  if (option.type && option.type == 'add') {
    state.userInfo.name = ''
    state.userInfo.cardType = '居民身份证'
    state.userInfo.idCard = ''
    state.userInfo.phone = ''
    state.userInfo.relation = ''
    state.userInfo.isDefault = false
    uni.setNavigationBarTitle({
      title: '添加就诊人'
    })
  } else {
    const params = {
      userId: option.userId,
      empi: option.empi
    }
    getPatInfo(params)
  }
})
onShow(() => {
  info.value = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : {}
})

const getPatInfo = (params: any) => {
  query_patient_detail(params).then((res) => {
    patientInfo.value = res.data
    state.userInfo.name = res.data.patName
    state.userInfo.idCard = res.data.idNo
    state.userInfo.phone = res.data.phone
    state.userInfo.relation = res.data.relation
    state.userInfo.isDefault = res.data.isDefault
    state.userInfo.cardType = res.data.idType
    state.userInfo.sex = res.data.gender
    state.userInfo.birthday = res.data.birthday.split(' ')[0]
    initDate.value = new Date(res.data.birthday)
    isDefault.value = res.data.isDefault
  })
}

const groupChange = (e) => {
  state.userInfo.sex = e.detail.value
}
const setBirth = (e) => {
  state.userInfo.birthday = e.detail.value
}

const selectRelation = (item: any) => {
  state.userInfo.relation = item.name
  show.value = false
}
const selectCardType = (item: any) => {
  state.userInfo.cardType = item.name
  // if (item.name == '居民身份证') {
  //   state.userInfo.sex = ''
  //   state.userInfo.birthday = ''
  // }
  show2.value = false
}
const switchChange = (e) => {
  state.userInfo.isDefault = e.detail.value
}

const deleteFamily = () => {
  if (isDefault.value) {
    uni.showToast({
      title: '不能删除默认就诊人！',
      icon: 'none'
    })
    return
  }
  if (patientInfo.value.hasVip) {
    uni.showToast({
      title: '该就诊人有会员记录，无法删除',
      icon: 'none'
    })
    return
  }
  modalShow.value = true
}

const deletePatient = () => {
  uni.showLoading()
  del_patient({ userId: info.value.userId, empi: patientInfo.value.empi }).then((res) => {
    if (info.value.patientInfo.empi == patientInfo.value.empi) {
      // 如果删除的是当前就诊人则将当前就诊人改为默认就诊人
      query_patient(info.value.userId).then((res) => {
        const defaultEmpi = res.data.find((item: any) => {
          return item.isDefault
        })
        base_info({ userId: info.value.userId, empi: defaultEmpi.empi }).then((res) => {
          const info = Object.assign({}, JSON.parse(uni.getStorageSync('userInfo')))
          info.patientInfo = res.data
          store.commit('SET_USERINFO', info)
          store.dispatch('app/IM_DESTROY')
        })
      })
    }
    uni.hideLoading()
    modalShow.value = false
    uni.showToast({
      title: '删除成功',
      icon: 'none',
      position: 'top',
      duration: 2000
    })
    setTimeout(() => {
      uni.navigateBack({ delta: 0 })
    }, 2000)
  })
}

const save = () => {
  const reg = /^[a-zA-Z0-9]{9}$/
  const phoneReg = /^1[3456789]\d{9}$/
  if (state.userInfo.name == '') {
    uni.showToast({
      title: '请输入姓名',
      icon: 'none'
    })
    return false
  }
  if (
    type.value == 'add' &&
    state.userInfo.cardType == '居民身份证' &&
    !validatorIdcard(state.userInfo.idCard)
  ) {
    uni.showToast({
      title: '请输入正确身份证号码',
      icon: 'none',
      position: 'top',
      //显示持续时间为 2秒
      duration: 2000
    })
    return false
  }
  if (
    type.value == 'add' &&
    state.userInfo.cardType !== '居民身份证' &&
    reg.test(state.userInfo.idCard) === false
  ) {
    uni.showToast({
      title: '请输入正确证件号',
      icon: 'none',
      position: 'top',
      duration: 2000
    })
    return false
  }
  if (phoneReg.test(state.userInfo.phone) === false) {
    uni.showToast({
      title: '请输入正确手机号',
      icon: 'none',
      position: 'top',
      duration: 2000
    })
    return false
  }
  if (state.userInfo.cardType !== '居民身份证' && !state.userInfo.sex) {
    uni.showToast({
      title: '请选择性别',
      icon: 'none',
      position: 'top',
      duration: 2000
    })
    return false
  }
  if (state.userInfo.cardType !== '居民身份证' && !state.userInfo.birthday) {
    uni.showToast({
      title: '请选择出生年月',
      icon: 'none',
      position: 'top',
      duration: 2000
    })
    return false
  }
  uni.showLoading()
  let params = {}
  if (type.value == 'add') {
    params = {
      userId: info.value.userId,
      idNo: state.userInfo.idCard,
      phone: state.userInfo.phone,
      relation: state.userInfo.relation,
      isDefault: state.userInfo.isDefault ? 1 : 0,
      patName: state.userInfo.name,
      gender: state.userInfo.sex,
      birthday: state.userInfo.birthday + ' 00:00:00',
      idType: state.userInfo.cardType
    }
  } else {
    params = {
      id: patientInfo.value.id,
      userId: info.value.userId,
      empi: patientInfo.value.empi,
      phone: state.userInfo.phone,
      relation: state.userInfo.relation,
      isDefault: state.userInfo.isDefault ? 1 : 0,
      patName: state.userInfo.name,
      gender: state.userInfo.sex,
      birthday: state.userInfo.birthday + ' 00:00:00',
      idType: state.userInfo.cardType
    }
  }
  if (state.userInfo.cardType == '居民身份证') {
    delete params.gender
    delete params.birthday
  }
  add_patient(params).then(async (ret) => {
    if (ret.code == 0) {
      uni.showToast({
        title: '保存成功'
      })
      uni.hideLoading()
      if (info.value.patientInfo.empi == patientInfo.value.empi) {
        // 如果是当前就诊人，则更新缓存中的信息
        base_info({ userId: info.value.userId, empi: patientInfo.value.empi }).then((res) => {
          info.value.patientInfo = res.data
          store.commit('SET_USERINFO', info.value)
        })
      }
      uni.navigateBack({ delta: 0 })
    }
  })
  return true
}
</script>

<style lang="scss" scoped>
.body {
  background: #f3f7f8;

  .tips {
    padding: 16rpx 32rpx;
    font-size: 28rpx;
    font-weight: 400;
    line-height: 39rpx;
    color: #ff7d00;
    background: #fff7e8;
  }

  .data_form {
    padding: 0 32rpx;
    margin: 24rpx 32rpx;
    background: #fff;
    border-radius: 16rpx;

    .form_item {
      position: relative;
      display: flex;
      align-items: center;
      height: 108rpx;
      border-bottom: 1rpx solid #e5e6eb;

      .title {
        width: 200rpx;
        font-size: 30rpx;
        font-weight: 500;
        color: #222;
      }

      .radio_group {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        width: 100%;
      }

      .form_input {
        width: 100%;
        font-size: 30rpx !important;
        font-weight: 400 !important;
        text-align: right !important;
        border: none;

        ::v-deep .uni-input-placeholder {
          color: #ccc !important;
          text-align: right;
        }

        ::v-deep .uni-input-input {
          // direction: rtl;
          color: #222 !important;
          text-align: right;
        }
      }

      .pop_select {
        position: relative;
        width: 470rpx;
      }

      .pop_input {
        width: 90%;
      }

      .img_more {
        position: absolute;
        top: 2rpx;
        right: 0;
        width: 40rpx;
        height: 40rpx;
      }
    }

    .form_item:last-child {
      border: none;
    }
    // 单选框样式
    ::v-deep .u-radio-group {
      gap: 24rpx;
      justify-content: flex-end;

      .u-radio__icon-wrap {
        width: 40rpx !important;
        height: 40rpx !important;
      }

      .u-icon__icon {
        font-size: 28rpx !important;
      }

      .u-radio__text {
        font-size: 28rpx !important;
        color: #222 !important;
      }
    }
  }

  ::v-deep .u-datetime-picker {
    display: none;
  }

  .u-popup {
    .title {
      height: 108rpx;
      font-size: 32rpx;
      font-weight: 500;
      line-height: 108rpx;
      color: #222;
      text-align: center;
      border-bottom: 1rpx solid #e5e6eb;
    }

    .lists {
      padding: 32rpx;

      .item {
        box-sizing: border-box;
        height: 96rpx;
        padding: 0 32rpx;
        margin-bottom: 24rpx;
        font-size: 32rpx;
        font-weight: 500;
        line-height: 96rpx;
        color: #222;
        text-align: center;
        background: #fafafa;
        border-radius: 8rpx;
      }

      .item:last-child {
        margin-bottom: 0;
      }
    }
  }

  .isdefault {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 32rpx;
    margin: 0 32rpx;
    background: #fff;
    border-radius: 16rpx;

    .label {
      font-size: 30rpx;
      font-weight: 500;
      color: #222;
    }

    ::v-deep .uni-switch-input::before {
      background: #e5e6eb;
    }
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    display: flex;
    gap: 24rpx;
    width: 100%;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    background: #fff;

    .confirm_btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 500;
      color: #fff;
      background: #00d1b6;
      border-radius: 44rpx;
    }

    .delete_btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 400;
      color: #666;
      background: #fff;
      border: 1px solid #cfcfcf;
      border-radius: 44rpx;
    }
  }

  ::v-deep .uicon-close {
    font-size: 32rpx !important;
    line-height: 50rpx !important;
  }

  ::v-deep .u-modal__title {
    font-size: 36rpx !important;
    font-weight: 500 !important;
    color: #222 !important;
  }

  ::v-deep .u-modal__content view {
    color: #666 !important;
  }
}
</style>
